#!/bin/bash

# 加载路径配置
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../config/paths.conf"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

error() {
    echo -e "${RED}[错误]${NC} $1"
}

info() {
    echo -e "${BLUE}[信息]${NC} $1"
}

# 检查必要组件
check_environment() {
    if ! command -v tcpdump &> /dev/null; then
        error "tcpdump 未安装，请先运行安装脚本"
        return 1
    fi
    
    if [ ! -d "$SCRIPTS_DIR" ]; then
        error "脚本目录不存在: $SCRIPTS_DIR"
        return 1
    fi
    
    return 0
}

# 显示状态
show_status() {
    log "=== 流量监控系统状态 ==="
    
    # 检查监控进程
    local monitor_pids=$(pgrep -f "tcpdump.*port (80|443)")
    if [ -n "$monitor_pids" ]; then
        log "监控进程运行中:"
        ps -p $monitor_pids -o pid,pcpu,pmem,cmd
    else
        log "监控进程: 未运行"
    fi

    # 显示实例信息
    log "实例信息:"
    $SCRIPTS_DIR/oss_uploader.sh info
    
    # 检查目录状态
    log "目录状态:"
    for dir in "$BASE_DIR" "$LOG_DIR" "$ARCHIVE_DIR"; do
        if [ -d "$dir" ]; then
            local size=$(du -sh "$dir" 2>/dev/null | cut -f1)
            local files=$(find "$dir" -type f 2>/dev/null | wc -l)
            log "  $dir: $size ($files 个文件)"
        else
            warn "  $dir: 不存在"
        fi
    done
    
    # 检查磁盘空间
    local disk_usage=$(df "$BASE_DIR" | awk 'NR==2 {print $5}')
    log "磁盘使用率: $disk_usage"
    
    # 检查定时任务
    log "定时任务:"
    if crontab -l 2>/dev/null | grep -q "traffic_monitor"; then
        crontab -l | grep "traffic_monitor"
    else
        log "  无相关定时任务"
    fi
}

# 启动监控
start_monitor() {
    local duration=${1:-7200}
    local oss_enabled=${2:-false}
    
    log "启动流量监控..."
    log "监控时长: $duration 秒 ($(($duration/3600)) 小时)"
    log "OSS上传: $oss_enabled"
    
    if ! check_environment; then
        return 1
    fi
    
    # 检查是否已在运行
    if pgrep -f "tcpdump.*port (80|443)" > /dev/null; then
        warn "监控已在运行中，先停止现有监控"
        stop_monitor
        sleep 2
    fi
    
    # 启动监控
    if [ "$oss_enabled" = "true" ]; then
        $SCRIPTS_DIR/start.sh $duration true
    else
        $SCRIPTS_DIR/start.sh $duration false
    fi
}

# 停止监控
stop_monitor() {
    log "停止流量监控..."
    
    if [ -f "$SCRIPTS_DIR/stop.sh" ]; then
        $SCRIPTS_DIR/stop.sh
    else
        warn "停止脚本不存在，强制停止监控进程..."
        pkill -f "tcpdump.*port (80|443)"
        pkill -f "netstat.*:80"
        sleep 2
        log "监控进程已停止"
    fi
}

# 执行清理
run_cleanup() {
    log "执行系统清理..."
    
    if [ -f "$SCRIPTS_DIR/auto_cleanup.sh" ]; then
        $SCRIPTS_DIR/auto_cleanup.sh run
    else
        error "清理脚本不存在"
        return 1
    fi
}

# 安装系统
install_system() {
    log "安装流量监控系统..."
    
    if [ -f "$SCRIPTS_DIR/install.sh" ]; then
        $SCRIPTS_DIR/install.sh
    else
        error "安装脚本不存在"
        return 1
    fi
}

# 设置定时清理
setup_scheduled_cleanup() {
    log "设置定时清理..."
    
    if [ -f "$SCRIPTS_DIR/auto_cleanup.sh" ]; then
        $SCRIPTS_DIR/auto_cleanup.sh setup
    else
        error "清理脚本不存在"
        return 1
    fi
}

# 生成报告
generate_report() {
    local timestamp=${1:-$(date +%Y%m%d_%H%M%S)}
    
    log "生成监控报告..."
    
    if [ -f "$SCRIPTS_DIR/generate_final_report.sh" ]; then
        $SCRIPTS_DIR/generate_final_report.sh $timestamp
    else
        warn "报告生成脚本不存在"
        # 手动生成简单报告
        local report_file="$LOG_DIR/system_report_$timestamp.txt"
        echo "=== 系统状态报告 ===" > $report_file
        echo "生成时间: $(date)" >> $report_file
        echo "主机名: $(hostname)" >> $report_file
        echo "" >> $report_file
        show_status >> $report_file
        log "报告已生成: $report_file"
    fi
}

# 显示使用说明
show_usage() {
    echo "流量监控系统管理工具"
    echo ""
    echo "用法: $0 {start|stop|status|cleanup|install|setup-cleanup|report|help} [参数]"
    echo ""
    echo "命令:"
    echo "  start [时长] [oss_enabled]  启动监控 (默认2小时, OSS关闭)"
    echo "  stop                        停止监控"
    echo "  status                      显示系统状态"
    echo "  cleanup                     执行清理"
    echo "  install                     安装系统组件"
    echo "  setup-cleanup               设置定时清理"
    echo "  report [时间戳]             生成报告"
    echo "  help                        显示此帮助"
    echo ""
    echo "示例:"
    echo "  $0 start 3600 true         启动1小时监控并启用OSS"
    echo "  $0 start                   启动2小时监控(默认)"
    echo "  $0 status                  显示系统状态"
    echo "  $0 cleanup                 执行清理"
}

case "$1" in
    "start")
        start_monitor "$2" "$3"
        ;;
    "stop")
        stop_monitor
        ;;
    "status")
        show_status
        ;;
    "cleanup")
        run_cleanup
        ;;
    "install")
        install_system
        ;;
    "setup-cleanup")
        setup_scheduled_cleanup
        ;;
    "report")
        generate_report "$2"
        ;;
    "help"|"--help"|"-h")
        show_usage
        ;;
    *)
        show_usage
        exit 1
        ;;
esac